<template>
  <div>
    <el-row>
      <el-form :model="userForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-col :span="12">
          <el-form-item label="用户名" label-width="70px" prop="username">
            <el-input v-model="userForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="70px" prop="password" v-if="!userForm.userId">
            <el-input v-model="userForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="头像" label-width="70px" prop="avatar">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="userForm.avatar" :src="'http://localhost:8080/'+userForm.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="号码" label-width="70px" prop="phonenumber">
            <el-input v-model="userForm.phonenumber" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" label-width="100px" prop="sex">
            <el-select v-model="userForm.sex" placeholder="请选择性别">
              <el-option label="男" value="0"></el-option>
              <el-option label="女" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门" label-width="100px" prop="deptId">
            <el-select v-model="userForm.deptId" placeholder="请选择所属部门">
              <el-option v-for="dl in deptList" :key="dl.id"
                         :label="dl.name"
                         :value="dl.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" label-width="100px" prop="roleId">
            <el-select v-model="userForm.roleId" placeholder="请选择扮演角色">
              <el-option v-for="rl in roleList" :key="rl.id"
                         :label="rl.name"
                         :value="rl.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备ID" label-width="100px" prop="deviceId">
            <el-select v-model="userForm.deviceId" placeholder="请选择设备">
              <el-option v-for="dil in deviceIdList" :key="dil.key"
                         :label="dil.key"
                         :value="dil.key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" label-width="100px">
            <el-input v-model="userForm.email" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" label-width="70px">
            <el-input type="textarea" v-model="userForm.remark" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close-dialog',false)">取 消</el-button>
      <el-button type="primary" @click="saveUser">确 定</el-button>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import esrequst from "@/utils/esrequst";

export default {
  name: "UserEdit",
  // 父组件的userId
  props: {
    id: {
      default: 0,
      required: true,
      type: Number
    }
  },
  data() {
    return {
      // 设备deviceId集合
      deviceIdList: [],
      dialogFormVisible: false,
      // 新增用户中的部门下拉框
      deptList: [],
      // 新增用户中的role角色下拉框
      roleList: [],
      // 新增的弹框
      userForm: {
        // 头像
        avatar: "",
      },

      // 校验规则
      rules: {
        username: [
          {required: true, message: '请输入你的用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入你的密码', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}
        ],
        avatar: [
          {required: true, message: '请选择你的头像', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择你的性别', trigger: 'blur'},
        ],
        phonenumber: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {min: 1, max: 11, message: '长度在 1 到 11 个字符', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '请选择所属部门', trigger: 'blur'},
        ],
        roleId: [
          {required: true, message: '请选择你的角色', trigger: 'blur'},
        ],
        deviceId: [
          {required: true, message: '请选择你的设备id', trigger: 'blur'},
        ],
      }
    }
  },
  created() {

    // 新增用户中部门的下拉框选择
    this.loadDept()
    // 新增用户中Role角色的下拉框选择
    this.loadRole()
    // 设备ID的下拉框
    this.loadDeviceId()
    // 数据回显
    if (this.id) {
      request(`user/${this.id}`).then(data => {
        this.userForm = data
      })
    }
  },
  methods: {
    // 通过到ES中去查询设备ID
    loadDeviceId() {
      esrequst("gyhat02/_search", "POST",
          {
            "size": 0,
            "aggs": {
              "group_by_userId": {
                "terms": {
                  "size": 20,
                  "field": "userId.keyword"
                }
              }
            }
          }).then(data => {
        this.deviceIdList = data.aggregations.group_by_userId.buckets
      })
    },

    // 保存发送的请求 有userId就进行修改，没有就进行新建
    async saveUser() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          request("user", this.userForm.userId ? "PUT" : "POST", this.userForm).then(() => {
            this.$message.success("编辑成功")
            this.$emit('close-dialog', true)
          }).catch(() => {
            this.$message.error("编辑失败")
          })
        } else {
          return false;
        }
      });
    },
    // user表中的deptId和dept表的name进行级联查询
    async loadDept() {
      let dataDept = await request("dept")
      this.deptList = dataDept
    },
    // user表中的roleId和role表的name进行级联查询
    async loadRole() {
      this.roleList = await request("role")
    },
    handleAvatarSuccess(res) {
      this.userForm.avatar = res
    },
    // 设置图片可以上传的格式和大小（不超过2M）
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG JPEG PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
/deep/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

/deep/
.el-form-item__content {
  line-height: 0;
}
</style>